const { oldSourceSelection: sourceSelection, tableSelection } = require("w-vue-middle/dataSourceService");
const glSqlEditor = require('w-vue-middle/components/glSqlEditor').default;
const $config = require("../config");
const $dataIntegration = require('w-vue-chongqing/src/api/dataIntegration');

export default {
  components: {
    sourceSelection,
    tableSelection,
    glSqlEditor
  },
  props: {
    tableCells: {
      type: Array,
      default: () => {
        return [];
      }
    },
    joinTable: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      activeTab: "table",
      inputTable: [],
      conditionList: [],
      viewTables: {},
      joinTypes: [
        { value: 'innerjoin', label: 'inner join' },
        { value: 'leftjoin', label: 'left join' },
        { value: 'rightjoin', label: 'right join' },
        { value: 'fulljoin', label: 'full join' },
        { value: 'crossjoin', label: 'cross join' },
      ],
      relationType: [],
    };
  },
  computed: {
    inputTableList() {
      return this.tableCells.filter(item => item.data.type == 'TableInput');
    },
    joinTables() {
      return this.tableCells.filter(item => item.data.type == 'TableInput' && !item.data.isMain).map(item => {
        return {
          value: item.data.asName,
          label: item.data.asName,
        }
      });
    },
  },
  created() {},
  methods: {
    /**
     * @Author: y_zp
     * @description: 切换关联表、关联条件
     */
    clickTab(val) {
      if(val == "join") {
        let notData = this.tableCells.find(item => {
          return item.data.type == 'TableInput' && (!item.data.dbId || !item.data.tableCode);
        });
        if(notData) {
          this.$message.warn("请完善关联表信息");
          return false
        }
        this.getConditionList();
      }
      this.activeTab = val;
    },
    /**
     * @Author: y_zp
     * @description: 切换主表
     */
    changeTableMain(row) {
      this.tableCells.forEach((item) => {
        if(item.data.type == 'TableInput') {
          if (item.data.id != row.data.id) {
            item.data.isMain = false;
          } else {
            item.data.isMain = true;
          }
        }
      });
    },
    /**
     * @Author: y_zp
     * @description: 设置默认主表
     */
    setTableMain() {
      let inputTable = this.tableCells.filter(item => item.data.type == 'TableInput');
      let hasMain = inputTable.find(item => {
        return item.data.isMain;
      })
      if (!hasMain && inputTable.length > 1) {
        this.$message.warning($t('必须设置一条数据是主表'));
        let defaultTable = this.tableCells.find(item => item.data.type == 'TableInput');
        defaultTable.data.isMain = true;
      }
    },

    /**
     * @Author: y_zp
     * @description: 关联表 - 切换数据源
     */
    changeSource(row) {
      this.getColumns(row);
    },
    /**
     * @Author: y_zp
     * @description: 关联表- 切换表
     */
    changeTable(row) {
      this.$set(row.data, "asName", row.data.tableCode);
      this.getColumns(row);
    },

    async getColumns(row) {
      if(!row.data.tableCode) {
        return false;
      }
      let { data } = await $dataIntegration.collectionDataInfo({
        clusterId: row.data.clusterId || "1",
        collectType: 'column',
        dsId: row.data.dbId,
        schema: row.data.schema,
        tableName: row.data.tableCode,
        useCache: false
      });
      row.data.columns = (data || []).map(item => {
        return {
          asName: item.asName || item.columnName,
          tableAsName: row.data.asName,
          tableCode: row.data.tableCode,
          tableId: row.data.tableId,
          tableName: row.data.tableName,
          ...item
        }
      });
      this.$emit("change")
    },
    /**
     * @Author: y_zp
     * @description: 新增关联表
     */
    toAddTable() {
      let tableInfo = JSON.DeepCopy($config.inputTableCell);
      tableInfo.data.id = `input_table_${Math.floor(Math.random() * 10000)}_${new Date().getTime()}`;
      this.tableCells.push({
        ...tableInfo
      });
      this.setTableMain();
    },
    /**
     * @Author: y_zp
     * @description: 删除关联表
     */
    toDelTable(row) {
      let idx = this.tableCells.findIndex(item => item.data.id == row.data.id);
      this.tableCells.splice(idx, 1);
      this.setTableMain();
    },
    /**
     * @Author: Jason Liu
     * @description: 获取关联表信息
     */
    getConditionList() {
      let viewTable = {};
      this.conditionList = this.inputTableList.map((table) => {
        let item = table.data;
        viewTable[item.asName] = [];
        let value = item.tableCode;
        if (item.asName) {
          value = item.asName;
        }
        return {
          value: value,
          label: item.asName,
          children: item.columns.map((column) => {
            viewTable[item.asName].push(column.columnName);
            return {
              value: column.columnName,
              label: column.description
                ? `${column.description}(${column.columnName})`
                : column.columnName,
            };
          }),
        };
      });
      this.viewTables = viewTable;
    },
    /**
     * @Author: y_zp
     * @description: 添加关联表
     */
    toAddJoin() {
      this.joinTable.data.joins.push({
        joinType: 'innerjoin', //关联方式
        right: {
          //关联表
          nodeId: undefined,
          tableCode: undefined,
          tableName: undefined,
          tableId: undefined,
          asName: undefined,
        },
        conditions: [
          //关联字段
          {
            type: 'def', //通过关系的方式关联
            script: undefined,
            leftmap: [],
            left: {
              nodeId: undefined,
              tableCode: undefined,
              tableName: undefined,
              tableId: undefined,
              asName: undefined,
              column: {},
            },
            relation: '=',
            rightmap: [],
            right: {
              nodeId: undefined,
              tableCode: undefined,
              tableName: undefined,
              tableId: undefined,
              asName: undefined,
              column: {},
            },
          },
        ],
      });
    },

    /**
     * @Author: y_zp
     * @description: 删除关联表
     */
    toDelJoin(i) {
      this.joinTable.data.joins.splice(i, 1);
    },
    /**
     * @Author: y_zp
     * @description: 添加关联表
     */
    parseJoinTable(join) {
      let refTable = this.tableCells.find((item) => {
        return item.data.type == "TableInput" && item.data.asName == join.asName;
      });
      if (refTable) {
        join.tableCode = refTable.data.tableCode;
        join.tableId = refTable.data.tableId;
        join.tableName = refTable.data.tableName;
        join.nodeId = refTable.data.nodeId;
      }
    },
    /**
     * @Author: y_zp
     * @description: 添加关联条件
     */
    toAddCondition(join, type = 'def') {
      join.conditions.push({
        type: type,
        script: undefined,
        leftmap: [],
        left: {
          nodeId: undefined,
          tableCode: undefined,
          tableName: undefined,
          tableId: undefined,
          column: {},
        },
        relation: '=',
        rightmap: [],
        right: {
          nodeId: undefined,
          tableCode: undefined,
          tableName: undefined,
          tableId: undefined,
          asName: undefined,
          column: {},
        },
      });
    },
    /**
     * @Author: y_zp
     * @description: 删除关联条件
     */
    toDelCondition(join, i) {
      join.conditions.splice(i, 1);
    },
    /**
     * @Author: y_zp
     * @description: 切换关联条件
     */
    changeCondition(row, map, send, join) {
      let value = row[map];
      this.tableCells.forEach((table) => {
        let data = table.data;
        if(data.type == "TableInput" && data.asName == value[0]) {
          row[send] = {
            nodeId: data.nodeId,
            tableCode: data.tableCode,
            tableName: data.tableName,
            asName: data.asName,
            tableId: data.tableId,
            column: data.columns.find((item) => {
              return item.columnName == value[1];
            }),
          };
        }
      });
      //自动补全左侧映射函数
      if (send == 'left' && row.rightmap.length == 0 && join.right.asName) {
        //左侧内容设置，并且右侧没有数据
        this.tableCells.forEach((table) => {
          let data = table.data;
          if(data.type == "TableInput" && data.asName == join.right.asName) {
            //做数据对齐
            let rightColumn = data.columns.find((v) => {
              return v.columnName == value[1] || v.asName == value[1];
            });
            if (rightColumn) {
              row.right = {
                nodeId: data.nodeId,
                tableCode: data.tableCode,
                tableName: data.tableName,
                asName: data.asName,
                tableId: data.tableId,
                column: rightColumn,
              };
              row.rightmap = [join.right.asName, value[1]];
            }
          }
        });
      }
    },

    /**
     * @Author: Jason Liu
     * @description: 查询关联表信息
     */
     filter(inputValue, path) {
      return path.some(
        (option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
      );
    },



  }
};